
<template>
    <div>
		<el-dialog draggable :title="title" :width="950"
			v-model="show" :close-on-click-modal="false" @close="emit('update:show', false)">
			<div class="dialog-content">
          <div class="toolbar tool-query">
            <el-row :gutter="0">
              <el-col :xs="8" :sm="4" class="col-title">表名</el-col>
              <el-col :xs="16" :sm="8" class="col-content">
                <el-input placeholder="" v-model="dataForm.TABLE_NAME" size="small"></el-input>
              </el-col>
              <el-col :xs="8" :sm="4" class="col-title">备注</el-col>
              <el-col :xs="16" :sm="8" class="col-content">
                <el-input placeholder="" v-model="dataForm.COMMENTS" size="small"></el-input>
              </el-col>
            </el-row>
          </div>
          <el-row :gutter="0" style="padding:10px;text-align:center;">
              <el-col :xs="4" :sm="1" class="col-title">
                 <el-button type="success" :icon="Plus" circle size="small" @click="handleAddRow" />
              </el-col>
          </el-row>
		  <el-table :data="dataForm.Columns" style="width: 100%" height="300px" size="small" empty-text="无数据">
            <el-table-column label="" width="48">
              <template #default="scope"> 
                <el-button type="danger" :icon="Edit" circle size="small" @click="handleRemove(scope)" />
              </template>
            </el-table-column>
            <el-table-column prop="ISKEY" label="键" width="40" align="center">
              <template #default="scope"> 
                <el-checkbox v-model="scope.row.ISKEY" :true-label="1" :false-label="0" size="small"
                @change="()=>{
                  if(scope.row.ISKEY == 0 || ['int','bigint','smallint','tinyint','numeric','decimal'].indexOf(scope.row.DATA_TYPE) == -1) 
                    scope.row.AUTOIN = 0 }"></el-checkbox>
              </template>
            </el-table-column>
            <el-table-column prop="AUTOIN" label="自增" width="40" align="center">
              <template #default="scope"> 
                <el-checkbox v-model="scope.row.AUTOIN" :true-label="1" :false-label="0" size="small"
                 :disabled="scope.row.ISKEY != 1 || ['int','bigint','smallint','tinyint','numeric','decimal'].indexOf(scope.row.DATA_TYPE) == -1"
                 @change="val=>{if(val){scope.row.NULLABLE='N'}}"></el-checkbox>
              </template>
            </el-table-column>
            <el-table-column prop="COLUMN_NAME" label="列名" width="180">
              <template #default="scope">
                <el-input placeholder="" v-model="scope.row.COLUMN_NAME" size="small"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="DATA_TYPE" label="类型" width="140">
              <template #default="scope">
                  <el-select v-model="scope.row.DATA_TYPE" placeholder="请选择" size="small" @change="handleDataTypeChange(scope.row, true)">
                    <el-option-group key="dthot" label="常用类型">
                      <el-option key="varchar" label="varchar" value="varchar"></el-option>
                      <el-option key="int" label="int" value="int"></el-option>
                      <el-option key="float" label="float" value="float"></el-option>
                      <el-option key="decimal" label="decimal" value="decimal"></el-option>
                      <el-option key="datetime" label="datetime" value="datetime"></el-option>
                    </el-option-group>
                    <el-option-group key="dtoth" label="其它类型">
                      <el-option key="integer" label="integer" value="integer"></el-option>
                      <el-option key="bigint" label="bigint" value="bigint"></el-option>
                      <el-option key="binary" label="binary" value="binary"></el-option>
                      <el-option key="bit" label="bit" value="bit"></el-option>
                      <el-option key="char" label="char" value="char"></el-option>
                      <el-option key="date" label="date" value="date"></el-option>
                      <el-option key="geometry" label="geometry" value="geometry"></el-option>  
                      <el-option key="numeric" label="numeric" value="numeric"></el-option>
                      <el-option key="real" label="real" value="real"></el-option>
                      <el-option key="smallint" label="smallint" value="smallint"></el-option>
                      <el-option key="text" label="text" value="text"></el-option>
                      <el-option key="timestamp" label="timestamp" value="timestamp"></el-option>
                      <el-option key="tinyint" label="tinyint" value="tinyint"></el-option>
                      <el-option key="blob" label="blob" value="blob"></el-option>
                      <el-option key="tinyblob" label="tinyblob" value="tinyblob"></el-option>
                      <el-option key="mediumblob" label="mediumblob" value="mediumblob"></el-option>
                      <el-option key="longblob" label="longblob" value="longblob"></el-option>
                    </el-option-group>
                  </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="DATA_LENGTH" label="长度" width="85">
              <template #default="scope">
                <el-input placeholder="" v-model="scope.row.DATA_LENGTH" size="small"
                   :disabled="scope.row.DATA_LENGTH_Disable"
                   ></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="DATA_SCALE" label="小数位" width="85">
              <template #default="scope">
                <el-input placeholder="" v-model="scope.row.DATA_SCALE" size="small"
                :disabled="scope.row.DATA_SCALE_Disable"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="DATA_DEFAULT" label="默认值" width="100">
              <template #default="scope">
                <el-input placeholder="" v-model="scope.row.DATA_DEFAULT" size="small"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="NULLABLE" label="非空" width="45" align="center">
              <template #default="scope">
                <el-checkbox v-model="scope.row.NULLABLE" true-label="N" false-label="Y" size="small"></el-checkbox>
              </template>
            </el-table-column>
            <el-table-column prop="COMMENTS" label="备注" width="150">
              <template #default="scope">
                <el-input placeholder="" v-model="scope.row.COMMENTS" size="small"></el-input>
              </template>
            </el-table-column>
          </el-table>
			</div>
			<template #footer>
          <span class="dialog-footer">
              <el-button size="small" @click="emit('update:show', false)">取消</el-button>
              <el-button size="small" type="primary" @click="submitForm">
                  提交</el-button>
          </span>
			</template>
		</el-dialog>
    </div>
</template>
<style scoped>
  .tool-query {
	border: 1px solid #ddd;
    line-height: 37px;
    border-radius: 5px;
  }
  .tool-query .col-title {
	  padding: 0 10px
  }
</style>
<script setup>
import { Plus, Edit } from '@element-plus/icons-vue'
import { post } from '/src/utils/http'
import { ElMessage } from 'element-plus'
import { watch,defineProps, defineEmits, onMounted, toRefs, nextTick, ref, computed } from 'vue'

const props = defineProps({
  show:Boolean,
  dbName: String,
  tableName: String,
  comments: String,
  dbConnStr: String
})

const { show,dbName,tableName,comments,dbConnStr } = toRefs(props)

const emit = defineEmits(['update:show'])

const title = computed(() => tableName.value ? '编辑': '新建')

const dataForm = ref({
  TABLE_NAME: '',
  EDIT_TABLE_NAME: '',
  COMMENTS: '',
  Columns:[],
})
const ColumnDefalut = ref({
  ISKEY: 0,
  EDIT_COLUMN_NAME: '',
  COLUMN_NAME: '',
  DATA_TYPE: 'varchar',
  DATA_LENGTH: '50', 
  DATA_SCALE: '',
  DATA_DEFAULT: '',
  NULLABLE: '', //可空, Y/N, 前端叫 非空, 要取反
  COMMENTS: '', //备注

  DATA_LENGTH_Disable: true,
  DATA_SCALE_Enable: true
})

function handleDataTypeChange(row, isEditing) {
  if(isEditing) {
      if(['char','nchar','nvarchar','varchar'].indexOf(row.DATA_TYPE) > -1) {
          row.DATA_LENGTH = '50'
      } else {
          row.DATA_LENGTH = ''
      }
  }
  
  row.DATA_LENGTH_Disable = [
      'bigint','bit','date','datetime','geometry','int','real','smallint', 
      'text','timestamp', 'tinyint','tinyblob','blob', 'mediumblob', 'longblob'
      ].indexOf(row.DATA_TYPE) > -1
      
  row.DATA_SCALE_Disable = [
      'numeric','decimal'
      ].indexOf(row.DATA_TYPE) == -1

  if(['int','bigint','smallint','tinyint'].indexOf(row.DATA_TYPE) == -1) {
    row.AUTOIN = 0
  }

  if(isEditing) {
      if(row.DATA_SCALE) {
          row.DATA_SCALE = '';
      }
  }
}
function handleAddRow(){
  var obj = Object.assign({ }, ColumnDefalut.value)
  
  var cn = 'Column1'
  for(var ci = 0; ci < dataForm.value.Columns.length + 1; ci++) {
      cn = 'Column' + (ci + 1)
      if(dataForm.value.Columns.filter(o => o.COLUMN_NAME == cn).length == 0)
          break;
  }
  obj.COLUMN_NAME = cn
  handleDataTypeChange(obj)
  dataForm.value.Columns.push(obj)
}
function handleRemove(scope){
  dataForm.value.Columns.splice(dataForm.value.Columns.indexOf(scope.row), 1)
}
function submitForm() {
  if(!dataForm.value.TABLE_NAME) {
      ElMessage({ 
          message: '表名是必填项',
          type: 'error',
      })
      return;
  }
  if(dataForm.value.Columns.length == 0) {
      ElMessage({ 
          message: '表至少包含一列',
          type: 'error',
      })
      return;
  }
  var autoc = dataForm.value.Columns.filter(o => o.ISKEY == 1 && o.AUTOIN == 1)
  if(autoc.length > 1) {
      ElMessage({ 
          message: '不允许多个自增列',
          type: 'error',
      })
      return;
  }
  var param = Object.assign(dataForm.value, {
      dbName: dbName.value,
      DbType: 'Mysql',
      dbConnStr: dbConnStr.value
  })
  post(`/api/${param.DbType}/Edit`, param)
  .then((res) => {
      if(!res.flag) {
          ElMessage({ 
              message: res.msg,
              type: 'error',
          })
          return;
      }
      ElMessage({ 
          message: '保存成功',
          type: 'success',
      })
      emit('update:show', false)
  })
}

const oldForm = JSON.stringify(dataForm.value)
watch(() => show.value, (val, oldval) => {
  if(val && tableName.value) { //显示且是编辑状态
    dataForm.value.TABLE_NAME = tableName.value
    dataForm.value.COMMENTS = comments.value || ''
    var param = { 
        DbType: 'Mysql',
        DbName: dbName.value,
        DbConnStr: dbConnStr.value,
        TABLE_NAME: dataForm.value.TABLE_NAME
    }
    post(`/api/${param.DbType}/GetTable`, param)
    .then((res) => {
        res.forEach(row => 
        {
          handleDataTypeChange(row)
          row.EDIT_COLUMN_NAME = row.COLUMN_NAME
        })
        dataForm.value.Columns = res
        dataForm.value.EDIT_TABLE_NAME = dataForm.value.TABLE_NAME
    })
  } else {
    dataForm.value = JSON.parse(oldForm)
  }
})
</script>
